package com.ieegu.replace.service;


import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class ReplaceServiceImpl implements ReplaceService {


    @Override
    public String doReplace(String text) {
        StringBuilder newStr = new StringBuilder();
        String[] strings = text.split("。");
        for (String string : strings) {
            String s1 = doTranslation(string + "。");
            String s2 = doTranslation(s1);
            newStr.append(s2);
        }
        return newStr.toString();
    }

    /**
     * 翻译
     *
     * @param text
     * @return
     */
    String doTranslation(String text) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("doctype", "json");
        paramMap.put("type", "AUTO");
        paramMap.put("i", text);
        String result = HttpRequest.post("http://fanyi.youdao.com/translate")
                .header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded")
                .form(paramMap)
                .timeout(20000)
                .execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        JSONArray translateResult = jsonObject.getJSONArray("translateResult");
        String tgt = translateResult.getJSONArray(0).getJSONObject(0).getStr("tgt");
        return tgt;
    }
}
